﻿﻿using System;
using System.Security.Cryptography;

namespace RSAExample
{
    public class MyClient
    {
        // static bool done = false;

        public static void run()
        {
            BdUtils.log("run!");
            // var main = new RSA();
            RSA.run();
        }

    }
    class RSA
    {
        static public void run()
        {

            var rsa = new RSACryptoServiceProvider();

            // Get the public and private keys as strings
            string publicKey = rsa.ToXmlString(false);
            string privateKey = rsa.ToXmlString(true);

            BdUtils.log("publicKey:", publicKey, "privateKey: ", privateKey);

            // Encrypt a message using the public key
            string message = "Hello, world!";
            byte[] encryptedMessage = Encrypt(message, publicKey);

            // Decrypt the message using the private key
            string decryptedMessage = Decrypt(encryptedMessage, privateKey);

            Console.WriteLine(decryptedMessage);
        }
        static byte[] Encrypt(string message, string publicKey)
        {
            // Convert the message to a byte array
            byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(message);

            // Convert the public key to a RSA parameter object
            RSAParameters rsaParams;
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(publicKey);
                rsaParams = rsa.ExportParameters(false);
            }

            // Encrypt the message using the public key
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaParams);
                return rsa.Encrypt(messageBytes, false);
            }
        }

        static string Decrypt(byte[] encryptedMessage, string privateKey)
        {
            // Convert the private key to a RSA parameter object
            RSAParameters rsaParams;
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(privateKey);
                rsaParams = rsa.ExportParameters(true);
            }

            // Decrypt the message using the private key
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaParams);
                byte[] decryptedMessage = rsa.Decrypt(encryptedMessage, false);
                return System.Text.Encoding.UTF8.GetString(decryptedMessage);
            }
        }
    }
}
